﻿using System.Collections;
using System.Text.RegularExpressions;

namespace 控制台输出测试
{
    internal class Program
    {
        static void Main(string[] args)
        { 
             byte[] b = { 0x0A, 0x01, 0x07, 0x12, 0x14, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00 }; // 0A 01 07 12 14 00 00 03 00 00 00
            //var cmd =  CRC16Help.CRC16(b);
            //Console.WriteLine(  cmd);

            //byte[] input = { 0x0A, 0x01, 0x07, 0x12, 0x14, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00 };
            //ushort crcValue = CalculateCRC16(input);
            //Console.WriteLine($"CRC16 校验值: 0x{Convert.ToString(crcValue, 16).PadLeft(4, '0')}");

            Console.WriteLine("----------------------------------");
            var input = "DY-K2-1-G1,DY-K2-1-G2,DY-K2-1-G3,DY-K2-1-E";
            var output = ProcessCodes(input);
            Console.WriteLine(output); // 输出: DY-K2-1-G1,DY-K2-1-E
        }

        public static string ProcessCodes(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            var codes = input.Split(',');
            var gFound = false;
            var result = new List<string>();

            foreach (var code in codes)
            {
                var trimmedCode = code.Trim();
                if (string.IsNullOrEmpty(trimmedCode))
                    continue;

                // 检查是否为G类代码（格式如DY-K2-1-G1）
                var match = Regex.Match(trimmedCode, @"^DY-K\d+-\d+-G\d+$");
                if (match.Success)
                {
                    if (!gFound)
                    {
                        result.Add(trimmedCode);
                        gFound = true;
                    }
                }
                else
                {
                    result.Add(trimmedCode);
                }
            }

            return string.Join(",", result);
        }


        static ushort CalculateCRC16(byte[] data)
        {
            const ushort polynomial = 0x1021;
            ushort crc = 0xFFFF;

            foreach (byte b in data)
            {
                crc ^= (ushort)(b << 8);
                for (int i = 0; i < 8; i++)
                {
                    if ((crc & 0x8000) != 0)
                    {
                        crc = (ushort)((crc << 1) ^ polynomial);
                    }
                    else
                    {
                        crc <<= 1;
                    }
                }
            }
            return crc;
        }
    }

    public class CRC16Help
    {
        #region 16位CRC校验

        /// <summary>
        /// CRC校验，参数data为byte数组
        /// </summary>
        /// <param name="data">校验数据，字节数组</param>
        /// <returns>字节0是高8位，字节1是低8位</returns>
        public static byte[] CRC16(byte[] data)
        {
            //crc计算赋初始值
            int crc = 0xffff;
            for (int i = 0; i < data.Length; i++)
            {
                crc = crc ^ data[i];
                for (int j = 0; j < 8; j++)
                {
                    int temp;
                    temp = crc & 1;
                    crc = crc >> 1;
                    crc = crc & 0x7fff;
                    if (temp == 1)
                    {
                        crc = crc ^ 0xa001;
                    }
                    crc = crc & 0xffff;
                }
            }
            //CRC寄存器的高低位进行互换
            byte[] crc16 = new byte[2];
            //CRC寄存器的高8位变成低8位，
            crc16[1] = (byte)((crc >> 8) & 0xff);
            //CRC寄存器的低8位变成高8位
            crc16[0] = (byte)(crc & 0xff);
            return crc16;
        }

        /// <summary>
        /// CRC校验，参数为空格或逗号间隔的字符串
        /// </summary>
        /// <param name="data">校验数据，逗号或空格间隔的16进制字符串(带有0x或0X也可以),逗号与空格不能混用</param>
        /// <returns>字节0是高8位，字节1是低8位</returns>
        public static byte[] CRC16(string data)
        {
            //分隔符是空格还是逗号进行分类，并去除输入字符串中的多余空格
            IEnumerable<string> datac = data.Contains(",") ? data.Replace(" ", "").Replace("0x", "").Replace("0X", "").Trim().Split(',') : data.Replace("0x", "").Replace("0X", "").Split(' ').ToList().Where(u => u != "");
            List<byte> bytedata = new List<byte>();
            foreach (string str in datac)
            {
                bytedata.Add(byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier));
            }
            byte[] crcbuf = bytedata.ToArray();
            //crc计算赋初始值
            int crc = 0xffff;
            for (int i = 0; i < crcbuf.Length; i++)
            {
                crc = crc ^ crcbuf[i];
                for (int j = 0; j < 8; j++)
                {
                    int temp;
                    temp = crc & 1;
                    crc = crc >> 1;
                    crc = crc & 0x7fff;
                    if (temp == 1)
                    {
                        crc = crc ^ 0xa001;
                    }
                    crc = crc & 0xffff;
                }
            }
            //CRC寄存器的高低位进行互换
            byte[] crc16 = new byte[2];
            //CRC寄存器的高8位变成低8位
            crc16[1] = (byte)((crc >> 8) & 0xff);
            //CRC寄存器的低8位变成高8位
            crc16[0] = (byte)(crc & 0xff);

            return crc16;

        }
        #endregion



        #region CheckCRC16 验证收到的CRC
        public static bool CheckCRC16(byte[] value)
        {
            return CheckCRC16(value, 160, 1);
        }
        private static bool CheckCRC16(byte[] value, byte CH, byte CL)
        {
            if (value == null)
            {
                return false;
            }

            if (value.Length < 2)
            {
                return false;
            }

            int num = value.Length;
            byte[] array = new byte[num - 2];
            Array.Copy(value, 0, array, 0, array.Length);
            byte[] array2 = CRC16(array, CH, CL);
            if (array2[num - 2] == value[num - 2] && array2[num - 1] == value[num - 1])
            {
                return true;
            }

            return false;
        }

        private static byte[] CRC16(byte[] value, byte CH, byte CL, byte preH = byte.MaxValue, byte preL = byte.MaxValue)
        {
            byte[] array = new byte[value.Length + 2];
            value.CopyTo(array, 0);
            byte b = preL;
            byte b2 = preH;
            for (int i = 0; i < value.Length; i++)
            {
                b = (byte)(b ^ value[i]);
                for (int j = 0; j <= 7; j++)
                {
                    byte b3 = b2;
                    byte b4 = b;
                    b2 = (byte)(b2 >> 1);
                    b = (byte)(b >> 1);
                    if ((b3 & 1) == 1)
                    {
                        b = (byte)(b | 0x80u);
                    }

                    if ((b4 & 1) == 1)
                    {
                        b2 = (byte)(b2 ^ CH);
                        b = (byte)(b ^ CL);
                    }
                }
            }

            array[array.Length - 2] = b;
            array[array.Length - 1] = b2;
            return array;
        }


        #endregion
    }
}
